﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using TemplateGenerator.Entities;

namespace TemplateGenerator.Logic {
	public static class WordSerializer {
		public static String XMLPath = Environment.CurrentDirectory + "\\Resources\\CustomTemplates.xml";

		public static void Serialize<T>(object instance) {
			try {
				XmlSerializer serializer = new XmlSerializer(typeof(T));

				if (!File.Exists(XMLPath)) {
					File.Create(XMLPath);
				}

				TextWriter writer = new StreamWriter(XMLPath);
				XmlSerializerNamespaces names = new XmlSerializerNamespaces();
				names.Add("", "");
				serializer.Serialize(writer, instance, names);
				writer.Close();
			} catch (Exception ex) {
				ExceptionHandler.WriteException(ex);
			}
		}

		public static T Deserialize<T>() {
			try {
				XmlSerializer serializer = new XmlSerializer(typeof(T));
				object data;

				if (!File.Exists(XMLPath)) {
					File.Create(XMLPath);
					return default(T);
				}

				using (FileStream reader = new FileStream((XMLPath), FileMode.Open)) {
					data = serializer.Deserialize(reader);
				}
				return (T)data;
			} catch (Exception ex) {
				ExceptionHandler.WriteException(ex);
				return default(T);
			}
		}

	}
}
